package com.shop.autoshop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.autoshop.pojo.Order;
import com.shop.autoshop.pojo.Product;
import com.shop.autoshop.pojo.Stock;
import com.shop.autoshop.pojo.WebConfig;
import com.shop.autoshop.service.OrderService;
import com.shop.autoshop.service.ProductService;
import com.shop.autoshop.service.StockService;
import com.shop.autoshop.service.WebConfigService;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private StockService stockService;
    @Autowired
    private WebConfigService webConfigService;


    @ResponseBody
    @PostMapping("/")
    public String pay(int id,int num,String contact,String password,int pay) throws IOException {

        WebConfig webConfig = webConfigService.getWebConfig();

        String token = webConfig.getWebPayToken(); //token
        String codepay_id = webConfig.getWebPayId() ;//payid

        Product pd = productService.findPdById(id);
        if(pd == null){
            return "{\n" +
                    "  \"code\":\"0\",\n" +
                    "  \"msg\":\"商品已下架或删除\",\n" +
                    "}";
        }

        if(num < 1){
            num = 1;
        }

        if(pd.getPdType() == 0){
            //卡密
            if(pd.getStNum() < num){
                //库存不足
                return "{\n" +
                        "  \"code\":\"0\",\n" +
                        "  \"msg\":\"商品库存不足\",\n" +
                        "}";
            }
        }else{
            //固定
            if(pd.getPdGdNum() < num){
                //库存不足
                return "{\n" +
                        "  \"code\":\"0\",\n" +
                        "  \"msg\":\"商品库存不足\",\n" +
                        "}";
            }
        }



        /**
         * 预占商品并加行锁
         */
        String goods = stockService.addLock(id, -1, num);
        if(goods.equals("0")){
            //库存不足
            return "{\n" +
                    "  \"code\":\"0\",\n" +
                    "  \"msg\":\"商品库存不足\",\n" +
                    "}";
        }



        /**
         * 产生随机订单号
         */
        int randNum = (int)Math.random()*100;
        Long time = System.currentTimeMillis();
        String randId = String.valueOf(time)+String.valueOf(randNum);


        /**
         * 接收参数 创建订单
         */


        String price=""+(pd.getPdPrice()*num); //表单提交的价格
        String type=""+pay; //支付类型  1：支付宝 2：QQ钱包 3：微信
        String pay_id=randId; //支付人的唯一标识

        String notify_url="http://localhost:8080/pay/notifyPay";//通知地址
        String return_url="http://localhost:8080/pay/returnPay";//支付后同步跳转地址

        //参数有中文则需要URL编码
        String url="http://api2.yy2169.com:52888/creat_order?id="+codepay_id+"&pay_id="+pay_id+"&price="+price+"&type="+type+"&token="+token+"&notify_url="+notify_url+"&return_url="+return_url;

        //获取JSON数据并存进数据库
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet;
        CloseableHttpResponse response = null;

        try {
            httpGet = new HttpGet(url+"&page=4");
            response = httpclient.execute(httpGet);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String res = EntityUtils.toString(entity);
                System.out.println(res); // 临时输出\

                JSONObject result = JSON.parseObject(res);
                String orderId = result.getString("order_id");

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String addtime = sdf.format(new Date());
                Double money = result.getDouble("money");
                if(pd.getPdType() == 0 ){
                    //卡密
                    orderService.addOrder(id,addtime,pay_id,orderId,num,money,contact,password,pay,goods,"");
                }else{
                    //固定
                    orderService.addOrder(id,addtime,pay_id,orderId,num,money,contact,password,pay,"",goods);
                }
            }
        } catch (java.io.IOException e) {
            // 忽略
        } finally {
            try {
                response.close();
            } catch (Exception ignore) {
            }
        }

        return "{\n" +
                "  \"code\":\"1\",\n" +
                "  \"msg\":\"\",\n" +
                "  \"url\":\""+url+"\"\n" +
                "}";
    }

    @GetMapping("/returnPay")
    public String returnPay(String pay_id,String pay_no,Double money){
        WebConfig webConfig = webConfigService.getWebConfig();

        String token = webConfig.getWebPayToken(); //token
        String codepay_id = webConfig.getWebPayId() ;//payid

        Order od = orderService.findByPayId(pay_id);
        System.out.println(Double.compare(od.getOdMoney(),money));
        if(od == null){
            //没有这个订单
            System.out.println("没有这个订单");
            return "redirect:/";
        }else if(Double.compare(od.getOdMoney(),money) != 0){
            System.out.println(od.getOdMoney());
            System.out.println(money);
            //金额不符合
            System.out.println("金额不符合");

            return "redirect:/";
        }else if(od.getOdState() == 1){
            //已处理过订单
            System.out.println("已处理过订单");
            return "redirect:/";
        }else if(pay_id == null || pay_no == null || money == null ){
            //缺少参数
            System.out.println("缺少参数");
            return "redirect:/";
        }

        //查询订单是否支付
        //参数有中文则需要URL编码
        String url= "http://api2.yy2169.com:52888/ispay?id="+codepay_id+"&order_id="+od.getOdOrderId()+"&token="+token;

        //System.out.println(url);
        //获取JSON数据并存进数据库
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet;
        CloseableHttpResponse response = null;

        try {
            httpGet = new HttpGet(url);
            response = httpclient.execute(httpGet);

            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String res = EntityUtils.toString(entity);
                System.out.println(res); // 临时输出

                JSONObject result = JSON.parseObject(res);

                if(result.getInteger("status") >= 1){
                    //支付成功
                    System.out.println("支付成功");
                    orderService.updateOrderStateAndTsNum(od.getOdId(),1,pay_no);

                    if(od.getOdGoodId() == null || od.getOdGoodId().equals("")){

                    }else{
                        String[] strIds = od.getOdGoodId().split(",");
                        int[] ids = new int[strIds.length];
                        int i = 0;
                        for (String s:strIds) {
                            ids[i] = Integer.valueOf(s);
                        }
                        stockService.updateStockState(ids,1);
                    }



                }else {
                    //支付失败
                    System.out.println("支付失败");
                }

            }
        } catch (java.io.IOException e) {
            // 忽略
        } finally {
            try {
                response.close();
            } catch (Exception ignore) {
            }
        }
        return "redirect:/query";
    }
}
